package com.rd.server.modules.login.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.rd.common.model.Result;
import com.rd.modules.group.AddGroup;
import com.rd.modules.user.model.ao.UserAO;
import com.rd.server.modules.login.service.LoginService;
import com.rd.server.modules.user.model.po.UserPO;
import com.rd.server.modules.user.service.UserService;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;


/**
 * 登录模块
 */
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class LoginController {

    private static final Logger log = LoggerFactory.getLogger(LoginController.class);
    private final WxMaService wxMaService;

    private final LoginService loginService;

    private final UserService userService;

    /**
     * 注册/登录
     *
     * @param userAO
     * @return
     */
    @PostMapping("/wx-login")
    public Result<SaTokenInfo> wxLogin(@Validated(AddGroup.class) @RequestBody UserAO userAO) {
        SaTokenInfo saTokenInfo = loginService.wxLogin(userAO);
        return Result.success(saTokenInfo);
    }


    /**
     * 退出登录
     *
     * @return
     */
    @PostMapping("logout")
    public Result<String> logout() {
        log.info("退出登录：【{}】", StpUtil.getLoginIdAsString());
        StpUtil.logout();
        return Result.success();
    }

    /**
     * 获取 openId
     *
     * @param code code码
     * @return
     */
    @GetMapping("/getOpenId")
    public Result<String> getOpenId(@RequestParam("code") String code) throws WxErrorException {
        WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
        String openId = session.getOpenid();
        UserPO userPO = userService.selectByOpenId(openId);
        Map<String, Object> extData = Map.of("isRegister", ObjectUtils.isNotEmpty(userPO));
        return Result.success(openId, extData);
    }
}